Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

311
Views
Cómo enviar "token" a "Api" en "reaccionar"

Soy un nuevo desarrollador. Si inicia sesión en nuestro sitio web, se creará JWT. Cuando presiono el botón, tengo que ponerlo en la API como backend. Y si la pantalla tiene éxito, se debe imprimir la dirección en la API. Si falla, debería mostrarse 'fallo de autenticación' en la pantalla. Quiero hacer esto. Por favor, ayúdame.

 import axios from 'axios'; import React, { useState } from 'react'; import { Button } from '@material-ui/core'; function TestPage() { const onLogin = () => { var variables = { email: email, password: password, }; Axios.post('/auth/login', variables).then((res) => { setCookie('token', res.payload.accessToken); setCookie('exp', res.payload.accessTokenExpiresIn); Axios.defaults.headers.common['Authorization'] = `Bearer ${res.payload.accessToken}`; Axios.get('/user/me').then((res) => { console.log(res); }); }); }; return ( <> <div> <Button variant="contained" color="primary" style={{ width: '200px' }} onClick={(e) => customFetch(e)}> address </Button> </div> {address && <div>{address}</div>} </> ); } export default TestPage;
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

En general, para cualquier operación de red, es útil saber cuándo está en curso, ha finalizado y/o tiene un error. Configuremos esto:

 const [isLoading, setIsLoading] = useState(false) const [data, setData] = useState(null) const [error, setError] = useState(null) // inside your `onLogin` function... setIsLoading(true); Axios.post('/auth/login', variables).then((res) => { setCookie('token', res.payload.accessToken); setCookie('exp', res.payload.accessTokenExpiresIn); Axios.defaults.headers.common['Authorization'] = `Bearer ${res.payload.accessToken}`; // bit messy using the same error state for both but you can always refactor Axios.get('/user/me').then((res) => { console.log(res); setData(res); // not sure where the actual data is with Axios }).catch(err => setError(err); }).catch(err => setError(err)); setIsLoading(false);

Durante su POST, establezca las variables de estado en consecuencia:

  1. Antes de la publicación, setIsLoading(true)
  2. En caso de éxito, setData(response.data) // whatever your payload might be
  3. En caso de error/fracaso, setError(error)

Ahora, en la devolución de su componente, puede representar condicionalmente sus diferentes estados, por ejemplo:

 // your component body if (isLoading) return ( // a loading state ) if (error) return ( // an error state // eg "Authentication Failure" ) return ( // your success/ideal state // eg: <> <div> <Button variant="contained" color="primary" style={{ width: '200px' }} onClick={(e) => customFetch(e)}> address </Button> </div> {address && <div>{address}</div>} </> )

Alternativamente, podría aprovechar las variables de forma ligeramente diferente:

 return ( <> <div> <Button variant="contained" color="primary" style={{ width: '200px' }} onClick={(e) => customFetch(e)} disabled={isLoading}> address </Button> </div> <div> {isLoading ? 'Checking...' : error !== null ? 'Something went wrong' : 'Ready to submit'} </div> </> )

Sin embargo, el estilo ternario puede ser un poco desordenado.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!